package com.yxw.live_vod_boot.mqtt;

import com.yxw.live_vod_boot.enums.MqttTopicEnum;
import com.yxw.live_vod_boot.service.OnDemandVideoReviewService;
import com.yxw.live_vod_boot.service.OrderService;
import com.yxw.live_vod_boot.utils.JsonUtils;
import com.yxw.live_vod_boot.vo.OrderVO;
import com.yxw.live_vod_boot.vo.VodMqttDelayedVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * mqtt客户端消息处理类
 *
 * @author qlinc
 */
@Slf4j
@Component
public class MqttMessageHandle implements MessageHandler {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OnDemandVideoReviewService onDemandVideoReviewService;

    @Override
    public void handleMessage(Message<?> message) throws MessagingException {       
        try {
            String topic = message.getHeaders().get(MqttHeaders.RECEIVED_TOPIC).toString();
            String data = new String((byte[]) message.getPayload(), StandardCharsets.UTF_8);
            log.info("消息主题:{},收到订阅消息:{},接收的Packet数据{}", topic, message, data);
            if (topic.startsWith(MqttTopicEnum.ORDER_TIMEOUT_TOPIC.getTopic())){
                log.info("开始处理订单超时任务......");
                OrderVO vo = JsonUtils.toObject(data,OrderVO.class);
                orderService.checkOrderExpiration(vo);
                log.info("订单超时任务处理完成,订单编号：【" + vo.getOrderNum() + "】,订单id：{}", vo.getOrderId());
            }
            if (topic.startsWith(MqttTopicEnum.VOD_PLAYURL_DELAYED_CONSUMER.getTopic())){
                log.info("开始获取点播视频播放地址任务......");
                VodMqttDelayedVo vo = JsonUtils.toObject(data, VodMqttDelayedVo.class);
                onDemandVideoReviewService.getVodPlayUrlByJobIdTask(vo);
                log.info("结束获取点播视频播放地址任务,参数{}",JsonUtils.toJson(vo));
            }
        } catch (Exception e) {
            log.error("mqtt客户端消息处理类异常:{}", e.getStackTrace());
            e.printStackTrace();
        }
    }
}

